package com.yznote.cloudesk.user.server.impl;

import com.yznote.cloudesk.common.constants.YCacheConstant;
import com.yznote.cloudesk.common.pojo.User;
import com.yznote.cloudesk.common.utils.YDUtils;
import com.yznote.cloudesk.cache.yCache.YCache;
import com.yznote.cloudesk.user.mapper.UserMapper;
import com.yznote.cloudesk.user.server.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    YCache yCache;

    @Override
    public List<User> getUserByName(String userName) {
        List<User> users = userMapper.getUserByName(userName);
        return users;
    }

    @Override
    public List<User> getAllUsers(Integer pageNum,Integer pageSize) {
        List<User> usersList = userMapper.getAllUsers();
        List<User> list = YDUtils.toListPage(pageNum, pageSize, usersList);
        for (User user : list) {
            if (yCache.contains(YCacheConstant.TOKEN,user.getUserId().toString())){
                user.setIsOnline(true);
            }else{
                user.setIsOnline(false);
            }
        }
        return usersList;
    }

    @Override
    public List<User> getAllOnlineUsers(Integer pageNum,Integer pageSize) {
        List<User> list = new ArrayList();
        Set<String> keysSet = yCache.getkeysByCacheName(YCacheConstant.TOKEN);
        list = YDUtils.toListPage(pageNum, pageSize, list);
        for (String key : keysSet) {
            //key的格式为tokenCache:xxxxxxxxxx;
            list.add(userMapper.getUserMsg(Long.parseLong(key.substring(11))));
        }
        return list;
    }

    @Override
    public Integer getAllOnlineUsersCount() {
        Set<String> keysSet = yCache.getkeysByCacheName(YCacheConstant.TOKEN);
        return keysSet.size();
    }
}
